package com.example.jc

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.jc.retrofit.MarsApi
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 * XiaoYao,万家灯火 华灯初上
 * @Description:
 * @Author: 肖垚 1094890313@qq.com
 * @create: 2021年11月19日 15:38
 * @Version 1.0
 **/
class MainViewModel : ViewModel() {

    // LiveData holds state which is observed by the UI
    // (state flows down from ViewModel)
    private val _name = MutableLiveData("222s")
    val name: LiveData<String> = _name

    // onNameChanged is an event we're defining that the UI can invoke
    // (events flow up from UI)
    fun onNameChanged(newName: String) {
        _name.value = newName
    }



    // The internal MutableLiveData String that stores the status of the most recent request
    private val _response = MutableLiveData<String>()

    // The external immutable LiveData for the request status String
    val response: LiveData<String>
        get() = _response

    /**
     * Call getMarsRealEstateProperties() on init so we can display status immediately.
     */
    init {
        getMarsRealEstateProperties()
    }

    /**
     * Sets the value of the status LiveData to the Mars API status.
     */
    private fun getMarsRealEstateProperties() {
        // TODO (05) Call the MarsApi to enqueue the Retrofit request, implementing the callbacks
        MarsApi.retrofitService.getProperties("rent").enqueue(object : Callback<String> {
            override fun onFailure(call: Call<String>, t: Throwable) {
                _response.value = "Failure: " + t.message
            }

            override fun onResponse(call: Call<String>, response: Response<String>) {
                _response.value = response.body()
            }
        })

//        _response.value = "Set the Mars API Response here!"
    }
}
